package com.ld.common.util.task.plugin;

import java.util.List;

import com.ld.admin.model.system.SysTimedtaskModel;
import com.ld.admin.service.system.SysTimedtaskService;
import com.ld.common.plugin.Plugin;
import com.ld.common.plugin.PluginInfo;
import com.ld.common.util.task.TaskManager;
import com.ld.shieldsb.annotation.util.TableNameUtil;
import com.ld.shieldsb.common.core.collections.ListUtils;
import com.ld.shieldsb.common.core.model.Result;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class TaskPlugin implements Plugin {
    private PluginInfo pluginInfo = new PluginInfo("定时任务插件", this); // 插件信息
    protected SysTimedtaskService service = new SysTimedtaskService();

    @Override
    public void initializePlugin() {
        String tableName = TableNameUtil.getTableName(SysTimedtaskModel.class);
        Result checkTableResult = service.checkTable(tableName);
        if (checkTableResult.getSuccess()) {
            // 查询所有文件任务并将其启动
            List<SysTimedtaskModel> modelList = service.getIsStartList(SysTimedtaskModel.class, 100); // 最多监控100个任务
            if (ListUtils.isNotEmpty(modelList)) {
                for (SysTimedtaskModel model : modelList) {
                    TaskManager.register(model);
                    try {
                        TaskManager.start(model.getJobId());
                    } catch (Exception e) {
                        log.error("启动任务出错！", e);
                    }
                }
            }
            // 扫描所有的task类（Runnable的实现类或者Thread的子类）
            TaskManager.loadTaskClass();
        } else {
            log.warn(checkTableResult.getMessage());
        }
    }

    @Override
    public void destroyPlugin() {
        TaskManager.shutdown();
    }

    @Override
    public PluginInfo getPluginInfo() {
        return pluginInfo;
    }
}